package edu.tyut.lingyunxing.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.tyut.lingyunxing.common.Constant;
import edu.tyut.lingyunxing.common.R;
import edu.tyut.lingyunxing.dto.UserLoginDTO;
import edu.tyut.lingyunxing.pojo.User;
import edu.tyut.lingyunxing.service.UserService;
import edu.tyut.lingyunxing.utils.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * DateTime: 2025/6/21 - 18:14
 * Author: Ycs
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public R<User> login(@RequestBody UserLoginDTO dto, HttpServletRequest request) {
        String account = dto.getAccount();
        String pw = dto.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account);
        User user = userService.getOne(queryWrapper);
        if (user != null && user.getPassword().equals(Md5Utils.md5(dto.getPassword()))) {
            request.getSession().setAttribute(Constant.SESSION_USER_KEY, user.getId());
            return R.success(user);
        } else {
            return R.error("密码错误！");
        }
    }
    
    @PostMapping("/register")
    public R<User> register(@RequestBody UserLoginDTO dto, HttpServletRequest request) {
        String account = dto.getAccount();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setAccount(account);
            user.setPassword(Md5Utils.md5(dto.getPassword()));
            userService.save(user);
            return R.success(user);
        } else {
            return R.error("该用户已存在");
        }
    }

    @PostMapping("/profile")
    public R<String> profile(@RequestBody User user, HttpServletRequest request) {
        Long id = user.getId();
        boolean b = userService.updateById(user);
        return b ? R.success("个人信息已更新") : R.error("个人信息修改失败！");
    }

    @PostMapping("/logout")
    public R<String> logout(@RequestBody User user, HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.SESSION_USER_KEY);
        return R.success("退出成功");
    }

    @GetMapping("/get")
    public R<User> get(HttpServletRequest request) {
        Long user = (Long) request.getSession().getAttribute(Constant.SESSION_USER_KEY);
        User u = userService.getById(user);
        if (u != null) {
            return R.success(u);
        } else {
            return R.error("未找到用户");
        }
    }

}
